package com.time.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.time.domain.User;
import com.time.mapper.UserMapper;
import com.time.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 张龙佼
 * @Description 用户信息 service接口实现类
 * @since 2020-10-14
 */

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean addUser(User user) {
        user.setPassword(DigestUtils.md5Hex(user.getPassword()));
        user.setStatus(1);

        return userMapper.insert(user) > 0;
    }

    @Override
    public boolean update(User user) {
        // 根据userId查询用户信息
        User userExist = userMapper.selectById(user.getUserId());

        // 判断获取的密码是否原密码相同，不同则加密码，否则不加密
        if (!user.getPassword().trim().equals(userExist.getPassword())) {
            user.setPassword(DigestUtils.md5Hex(user.getPassword()));
        }

        return userMapper.updateById(user) > 0;
    }

    @Override
    public User login(String userId, String password) {
        // md5对密码加密
        password = DigestUtils.md5Hex(password);

        // 登录验证查询
        LambdaQueryWrapper<User> userQuery = new LambdaQueryWrapper<>();
        userQuery.eq(User::getUserId, userId).eq(User::getPassword, password);

        return userMapper.selectOne(userQuery);
    }
}
